/*
 * Copyright (C) 2012 yueyueniao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wzm.moviepic.fragment;

import java.io.File;
import java.util.ArrayList;

import com.wzm.bean.HistoryBean;
import com.wzm.bean.MovieInfo;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.moviepic.R;
import com.wzm.moviepic.slidingmenu.Main1Activity;
import com.wzm.utils.FileUtils;
import com.wzm.utils.Logger;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;


public class HistoryFragment extends Fragment {

	private ListView historyList = null;
	private HistoryAdapter pd = null;
	private Context mContext;
	private ArrayList<HistoryBean> hList = new ArrayList<HistoryBean>();
	
	
	private ImageView btn_imgdelall = null;
	private LinearLayout lly_delall = null;
	
	//手势
	private GestureDetector detector = null;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = getActivity();
		
		View view = inflater.inflate(R.layout.page2, null);
		historyList = (ListView)view.findViewById(R.id.historyList);
		pd = new HistoryAdapter(mContext,hList);
		historyList.setAdapter(pd);
		
		getHistoryInfo();
		
		
		historyList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				HistoryBean hb = hList.get(position);
				MovieInfo mi = new MovieInfo();
				mi.setName(hb.getMoviename());
				Logger.error("movieid:"+hb.getMovieid());
				mi.setId(String.valueOf(hb.getMovieid()));
				Intent intent = new Intent(mContext,ViewPagerActivity.class);			
				Bundle bundle = new Bundle();
				bundle.putSerializable("movieinfo", mi);
				intent.putExtras(bundle);
				mContext.startActivity(intent);
				mi = null;			
			}
		});
		
		
		
		
		
		detector = new GestureDetector(getActivity(),new OnGestureListener() {
			
			@Override
			public boolean onSingleTapUp(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onShowPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
					float distanceY) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onLongPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
					float velocityY) {
				// TODO Auto-generated method stub
				
				if (e1.getX() - e2.getX() > 120) {
					//Logger.info("向左...");
					
		            return true;
		        } else if (e1.getX() - e2.getX() < -120) {

		        	((Main1Activity)mContext).showcenter();

		            return true;
		        }
				
				return false;
			}
			
			@Override
			public boolean onDown(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		historyList.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return detector.onTouchEvent(event);
			}
		});
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		btn_imgdelall = (ImageView)view.findViewById(R.id.btn_imgdelall);
		btn_imgdelall.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Logger.info("showDialog");
				showDelConfig(getActivity());
			}
		});
		
		return view;
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		
		
		super.onActivityCreated(savedInstanceState);
	}
	
	public void getHistoryInfo()
	{
		
		//查询数据库
		Cursor cursor = DBHelper.getInstance(mContext).querySql("select * from history order by addtime desc", null);
		if(null!=cursor&&cursor.getCount()>0)
		{
			Logger.error("有书签记录:"+cursor.getCount());
			hList.clear();
			if(cursor.moveToFirst())
    		{				
				do{					
					HistoryBean hb = new HistoryBean();
					hb.setMovieid(cursor.getInt(1));
					hb.setMark(cursor.getInt(2));
					hb.setSize(cursor.getInt(5));
					hb.setMoviename(cursor.getString(3));
					hb.setAddtime(cursor.getString(4));
					hList.add(hb);
					hb = null;
					//Logger.info(cursor.getString(3));
				}while(cursor.moveToNext());
				pd.notifyDataSetChanged();				
    		}
		}else{
			hList.clear();
			pd.notifyDataSetChanged();	
			Logger.error("没有书签记录");
		}
		if(null!=cursor)
		{
			cursor.close();
		}		
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		getHistoryInfo();
		super.onResume();
	}
	
	
	public void showDelConfig(final Context context) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder
            .setMessage("是否删除全部记录?")
            .setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        DBHelper.getInstance(getActivity()).excutesql("delete from history");
                        getHistoryInfo();
                    }
                }
            ).setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }
            );
        alertBuilder.create().show();
    }
	
	
}

